<?php

namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;
use mailer\facade\Mailer;
use app\model\Site;
use app\model\Log;


class Code extends BaseController
{
    static public function send() // 发送
    {
        // 引入邮件配置文件
        $smtp = include("../config/mailer.php");
        if($smtp['password'] != Site::get("smtp_pw"))//配置不同
        {
            $host = Site::get("smtp_host");
            $name = Site::get("smtp_name");
            $pw = Site::get("smtp_pw");
            $port = Site::get("smtp_port");
            $username = Site::get("smtp_username");
            $data=<<<_
            <?php

/**
* 配置文件
*/
return [
'scheme'   => 'smtp',// "smtps": using TLS, "smtp": without using TLS.
'host'     => '$host', // 服务器地址
'username' => '$username', // 用户名
'password' => '$pw', // 密码
'port'     => $port, // SMTP服务器端口号,一般为25
'options'  => [], // See: https://symfony.com/doc/current/mailer.html#tls-peer-verification
// 'dsn'             => '',
'embed'    => 'cid:', // 邮件中嵌入图片元数据标记
'from'     => [
    'address' => '$username',
    'name'    => '$name',
]
];
_;
            file_put_contents("../config/mailer.php", $data);
            return json(array('code' => 403, 'msg' => '后台配置已刷新，请重新发送'));
        }

        // 获取用户输入的邮箱地址
        $email = Request::post('email');

        // 查询数据库中是否存在该邮箱地址
        $db_code = Db::connect()->table('site_code')->where('email', $email)->select()->toArray(); // 查询数据

        // 如果数据库中不存在该邮箱地址
        if (count($db_code) == 0) { // 不存在
            // 生成随机验证码
            $code = rand(100000, 999999);
            $data = [
                'email' => $email,
                'time' => time(),
                'code' => $code
            ];

            // 插入数据到数据库
            Db::name('site_code')->insert($data);

            
            // 发送验证码邮件
            Mailer::from($smtp['username'])
                ->to($email)
                ->subject('请查收您的验证码')
                ->text("欢迎使用 DuckSite~ 您的验证码是 $code ，如非本人操作请忽略！")
                ->send();

            // 返回发送成功信息
            return json(array('code' => 200, 'msg' => '发送成功'));
        } else {
            $time = $db_code[0]["time"];
            if ($time + 60 > time()) { // 不允许发送
                return json(array('code' => 403, 'msg' => '请稍等一会儿'));
            } else {
                $code = rand(100000, 999999);

                Db::name('site_code')
                    ->where('email', $email)
                    ->update(['code' => $code, 'time' => time()]);

                $smtp = include("../config/mailer.php");

                Mailer::from($smtp['username'])
                    ->to($email)
                    ->subject('请查收您的验证码')
                    ->text("欢迎使用 DuckSite~ 您的验证码是 $code ，如非本人操作请忽略！")
                    ->send();

                return json(array('code' => 200, 'msg' => '发送成功'));
            }
        }
    }

    static public function accept() // 验证
    {
        $email = Request::post('email', '');
        $code = Request::post('code', '');
        $db_code = Db::connect()->table('site_code')->where('email', $email)->select()->toArray(); // 查询数据

        if (count($db_code) == 0) { // 不存在
            return json(array('code' => 404, 'msg' => '验证失败'));
        } else {
            $time = $db_code[0]["time"];

            if ($time + 300 > time()) { // 允许
                if ($db_code[0]['code'] == $code) { // 验证码正确
                    Db::table('site_code')->delete($email);
                    return json(array('code' => 200, 'msg' => '验证成功'));
                } else {
                    return json(array('code' => 403, 'msg' => '验证失败'));
                }
            } else { // 不允许，已超时
                return json(array('code' => 502, 'msg' => '验证失败'));
            }
        }
    }
}
